package com.jstyle.jclife.activity;


import android.Manifest;
import android.app.Dialog;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PersistableBundle;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.Vibrator;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.telecom.TelecomManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.internal.telephony.ITelephony;
import com.jstyle.blesdk.Util.ResolveUtil;
import com.jstyle.blesdk.Util.SingleDealData;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceConst;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.DeviceBean;
import com.jstyle.blesdk.model.GetData;
import com.jstyle.blesdk.model.Notifier;
import com.jstyle.blesdk.model.SetPersonalInfo;
import com.jstyle.blesdk.model.StepModel;
import com.jstyle.jclife.NetWork.NetWorkException;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.app.MyApplication;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.daoManager.HealthDataDaoManager;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.NotifyDataDaoManager;
import com.jstyle.jclife.daoManager.SleepDataDaoManager;
import com.jstyle.jclife.daoManager.StepDataDaoManager;
import com.jstyle.jclife.daoManager.StepDetailDataDaoManager;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.fragment.EcgFragment;
import com.jstyle.jclife.fragment.EcgHistoryFragment;
import com.jstyle.jclife.fragment.ExerciseFragment;
import com.jstyle.jclife.fragment.HealthFragment;
import com.jstyle.jclife.fragment.Heart1810Fragment;
import com.jstyle.jclife.fragment.HomePageFragment;
import com.jstyle.jclife.fragment.SettingFragment;
import com.jstyle.jclife.model.BleData;

import com.jstyle.jclife.model.Device1790;

import com.jstyle.jclife.model.Device1810;
import com.jstyle.jclife.model.HealthData;
import com.jstyle.jclife.model.HeartData;


import com.jstyle.jclife.model.JstyleDevice;
import com.jstyle.jclife.model.NotifyData;
import com.jstyle.jclife.model.SleepData;
import com.jstyle.jclife.model.SosContact;
import com.jstyle.jclife.model.StepData;
import com.jstyle.jclife.model.StepDetailData;
import com.jstyle.jclife.model.UpdateData;
import com.jstyle.jclife.model.UploadData;
import com.jstyle.jclife.model.UserInfo;
import com.jstyle.jclife.utils.AppUpdateUtils;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.DfuUtil;
import com.jstyle.jclife.utils.GlobalConast;
import com.jstyle.jclife.utils.GlobalConst;
import com.jstyle.jclife.utils.ImageUtils;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.NotificationListener;
import com.jstyle.jclife.utils.PermissionsUtil;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.RxBus;
import com.jstyle.jclife.utils.SchedulersTransformer;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.utils.UploadUtils;
import com.jstyle.jclife.utils.ZipUtils;
import com.jstyle.jclife.view.TipsDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ezy.assist.compat.SettingsCompat;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class MainActivity extends BaseActivity implements AMapLocationListener ,SettingFragment.OnFragmentInteractionListener{

    @BindView(R.id.frameLayout_content)
    FrameLayout frameLayoutContent;
    @BindView(R.id.RadioButton_homePage)
    RadioButton RadioButtonHomePage;
    @BindView(R.id.RadioButton_exercise)
    RadioButton RadioButtonExercise;
    @BindView(R.id.RadioButton_more)
    RadioButton RadioButtonMore;
    @BindView(R.id.RadioButton_health)
    RadioButton RadioButtonHealth;
    @BindView(R.id.RadioButton_setting)
    RadioButton RadioButtonSetting;
    @BindView(R.id.RadioGroup_home)
    RadioGroup RadioGroupHome;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    private FragmentManager fragmentManager;
    private static final int FRAGMENT_HOME = 1;
    private static final int FRAGMENT_EXERCISE = 2;
    private static final int FRAGMENT_HEALTH = 3;
    private static final int FRAGMENT_HEALTH1810 = 6;
    private static final int FRAGMENT_HEALTH1790= 7;
    private static final int FRAGMENT_SETTING = 4;
    private static final int FRAGMENT_ECG = 5;
    private HomePageFragment homePageFragment;
    private ExerciseFragment exerciseFragment;
    private HealthFragment healthFragment;
    private SettingFragment settingFragment;
    private EcgFragment ecgFragment;
    EcgHistoryFragment ecgHistoryFragment;
    Heart1810Fragment heart1810Fragment;
    private List<Map<String, String>> list = new ArrayList<>();
    private List<Map<String, String>> listDetail = new ArrayList<>();
    private List<Map<String, String>> listSleep = new ArrayList<>();
    private List<Map<String, String>> listHeart = new ArrayList<>();//单次心率历史数据
    private List<Map<String, String>> listHistoryHeart = new ArrayList<>();
    private List<Map<String, String>> listHrv = new ArrayList<>();
    private boolean isNeedDelay;
    // private TelephonyManager tm;
    //private ListenerReceiver receiver;
    private Ringtone ringtone;
    private Vibrator vibrator;
    private AlertDialog ringAlertDialog;
    private Dialog batteryDialog;
    private AlertDialog OverlaysDialog;
    boolean isDetailBefore;
    String lastDetailTime;
    boolean isSleepBefore;
    String lastSleepTime;
    boolean isHeartBefore;
    String lastHeartTime;
    private ListenerReceiver receiver;
    private TelephonyManager tm;
    private AMapLocationClient aMapLocationClient;
    private Integer batteryValue;
    private boolean isSyc;
    private String deviceAddress;
    private List<Fragment> fragmentList=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "onCreate: ");
        ExerciseRecordListActivity.needAutoSyc = true;
        ButterKnife.bind(this);
        toggleNotificationListenerService();
        deviceAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        fragmentManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            fragmentList = fragmentManager.getFragments();
            for(Fragment fragment:fragmentList){
                Log.i(TAG, "onCreate: f "+fragment.getClass().getSimpleName());
            }
        }
        init();
        registerReceiver();
        Connect();
        checkAppVersion();

    }

    private void initLocation(){
        Log.i(TAG, "initLocation: ");
        aMapLocationClient=new AMapLocationClient(this);
        aMapLocationClient.setLocationListener(this);
        AMapLocationClientOption aMapLocationClientOption=new AMapLocationClientOption();
        aMapLocationClientOption.setOnceLocation(true);
        aMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        aMapLocationClient.setLocationOption(aMapLocationClientOption);
        aMapLocationClient.startLocation();
    }
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.i(TAG, "onLocationChanged: ");
        double lat=aMapLocation.getLatitude();
        double lng=aMapLocation.getLongitude();
        sendSos(lat,lng);

    }
    @Override
    protected void onResume() {
        super.onResume();
        deviceAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        deviceType= MyApplication.getJstyleDevice().getDeviceNo();
      //  ivMore.setImageResource(deviceType.equals(JstyleDevice.device_1790_01)?R.drawable.more_checked:R.drawable.more_add);
        checkAppVersion();
    }

    private void toggleNotificationListenerService() {
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(this, NotificationListener.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

        pm.setComponentEnabledSetting(new ComponentName(this, NotificationListener.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void readBatteryAndVersion() {
        if(isSyc)return;
        if (BleManager.getInstance().isConnected()) {
            offerData(SendCmdState.READ_DEVICE_BATTERY);
            offerData(SendCmdState.READ_VERSION);
            offerData();
        }
    }

    class ListenerReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals("android.provider.Telephony.SMS_RECEIVED")) {
                Object[] pdus = (Object[]) intent.getExtras().get("pdus");
                Notifier notifierSms = new Notifier();
                JstyleDevice jstyleDevice= MyApplication.getJstyleDevice();
                if(jstyleDevice!=null)notifierSms.setNotifierType(jstyleDevice.getNotifierType());
                for (Object pdu : pdus) {
                    SmsMessage smsMessage = SmsMessage
                            .createFromPdu((byte[]) pdu);
                    String sender = smsMessage.getDisplayOriginatingAddress();
                    String info = smsMessage.getDisplayMessageBody();
                    notifierSms.setInfo(sender + info);
                    notifierSms.setType(Notifier.Data_Sms);
                    sendNotify(notifierSms, 1);
                }
            } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
                int state = tm.getCallState();
                int type = state == TelephonyManager.CALL_STATE_RINGING ? Notifier.Data_Tel : Notifier.Data_Stop_Tel;
                String incomingNumber = intent.getStringExtra(
                        TelephonyManager.EXTRA_INCOMING_NUMBER);
                Log.i(TAG, "onReceive: "+incomingNumber);
                Notifier notifierPhone = new Notifier();
                JstyleDevice jstyleDevice= MyApplication.getJstyleDevice();
                if(jstyleDevice!=null)notifierPhone.setNotifierType(jstyleDevice.getNotifierType());
                notifierPhone.setInfo(TextUtils.isEmpty(incomingNumber) ? "" : ResolveData.getPeople(incomingNumber, MainActivity.this));
                notifierPhone.setType(type);
                sendNotify(notifierPhone, 0);
            }else if(action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)){
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                        BluetoothAdapter.ERROR);
                switch (state) {
                    case BluetoothAdapter.STATE_ON:
                        RadioGroupHome.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                final String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
                                if(!TextUtils.isEmpty(address)){
                                    BleManager.getInstance().reConnect();
                                }
                            }
                        },600);


                        Log.i(TAG, "onReceive: 开启蓝牙");
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        BleManager.getInstance().disconnectDeviceAndClose();
                        Log.i(TAG, "onReceive: 关闭蓝牙");
                        break;

                }
            }
        }
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
      //  filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        receiver = new ListenerReceiver();
        registerReceiver(receiver, filter);
    }

    private void sendNotify(Notifier notifier, long id) {
        final NotifyData notifyData = getNotifyData(id);
        if (!notifyData.isEnable()) return;
        BleManager.getInstance().writeValue(
                SingleDealData.sendData(SendCmdState.SET_NOTIFIER, notifier));
    }

    private NotifyData getNotifyData(long id) {
        NotifyData notifyData = NotifyDataDaoManager.getNotifyData(id);
        return notifyData;
    }

    private boolean checkDialogPermission() {
        boolean isEnable = false;

        if (!SettingsCompat.canDrawOverlays(this)) {
            if (OverlaysDialog == null) {
                OverlaysDialog = new AlertDialog.Builder(this,R.style.appalertdialog).setMessage(R.string.check_dialog_tips)
                        .setPositiveButton(R.string.require_allow, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                                if (getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0){
                                    startActivity(intent);
                                }else{
                                    SettingsCompat.manageDrawOverlays(MainActivity.this);
                                }



                            }
                        }).setNegativeButton(R.string.cancel, null).setCancelable(false).create();

            }
            if (!OverlaysDialog.isShowing()) OverlaysDialog.show();
        } else {
            isEnable = true;
        }

        return isEnable;
    }

    private void init() {
        checkDialogPermission();
        checkStoragePermissions();
        tm = (TelephonyManager) getSystemService(
                Service.TELEPHONY_SERVICE);

        startTransaction(FRAGMENT_HOME);
        RadioGroupHome.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int fragmentId = 0;
                switch (checkedId) {
                    case R.id.RadioButton_exercise:
                        fragmentId = FRAGMENT_EXERCISE;
                        break;
                    case R.id.RadioButton_health:
                        fragmentId = getFragmentHealthId();
                        break;
                    case R.id.RadioButton_homePage:
                        fragmentId = FRAGMENT_HOME;
                        break;
                    case R.id.RadioButton_more:
                        return;
                    case R.id.RadioButton_setting:
                        fragmentId = FRAGMENT_SETTING;
                        break;
                }
                Log.i(TAG, "onCheckedChanged: " + checkedId);

                startTransaction(fragmentId);
            }
        });

    }
    private void checkStoragePermissions() {
        PermissionsUtil.requestPermissions(this, new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                HomePageFragment homePageFragment= (HomePageFragment) findFragment(FRAGMENT_HOME);
                if (homePageFragment != null) homePageFragment.updateUserInfo();
            }

            @Override
            public void NeverAskAgain() {

            }

            @Override
            public void disallow(String name) {

            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_CONTACTS);
    }

//    protected void startTransaction(int fragmentId) {
//        if (fragmentId == -1) return;
//        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//        hideFragment(fragmentTransaction);
//        switch (fragmentId) {
//            case FRAGMENT_HOME:
//                if (homePageFragment == null) {
//                    homePageFragment = new HomePageFragment();
//                    fragmentTransaction.add(R.id.frameLayout_content, homePageFragment);
//                } else {
//                    fragmentTransaction.show(homePageFragment);
//                }
//                break;
//            case FRAGMENT_EXERCISE:
//                if (exerciseFragment == null) {
//                    exerciseFragment = new ExerciseFragment();
//                    fragmentTransaction.add(R.id.frameLayout_content, exerciseFragment);
//                } else {
//                    fragmentTransaction.show(exerciseFragment);
//                }
//                break;
//            case FRAGMENT_HEALTH:
//                showHealthFragment(fragmentTransaction);
//                break;
//            case FRAGMENT_SETTING:
//                if (settingFragment == null) {
//                    settingFragment = new SettingFragment();
//                    fragmentTransaction.add(R.id.frameLayout_content, settingFragment);
//                } else {
//                    fragmentTransaction.show(settingFragment);
//                }
//                break;
//            case FRAGMENT_ECG:
//                if (ecgFragment == null) {
//                    ecgFragment = new EcgFragment();
//                    fragmentTransaction.add(R.id.frameLayout_content, ecgFragment);
//                } else {
//                    fragmentTransaction.show(ecgFragment);
//                }
//                break;
//        }
//
//        fragmentTransaction.commitAllowingStateLoss();
//    }
    int selectedFragmentId=-1;
    protected void startTransaction(int fragmentId) {
        //  Log.i(TAG, "startTransaction: "+fragmentId);
        if (fragmentId <1||fragmentId==selectedFragmentId) return;
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragment(fragmentTransaction);
        Fragment fragment = findFragment(fragmentId);
        if (fragment != null) {
            Log.i(TAG, "startTransaction: "+fragment.getClass().getSimpleName());
            fragmentTransaction.show(fragment);
        } else {
            switch (fragmentId) {
                case FRAGMENT_HOME:
                    fragment = new HomePageFragment();
                    break;
                case FRAGMENT_EXERCISE:
                    fragment = new ExerciseFragment();
                    break;
                case FRAGMENT_HEALTH:
                    fragment=new HealthFragment();
                    break;
                case FRAGMENT_HEALTH1790:
                    fragment= new EcgHistoryFragment();
                    break;
                case FRAGMENT_HEALTH1810:
                    fragment=new Heart1810Fragment();
                    break;
                case FRAGMENT_SETTING:
                    fragment = new SettingFragment();
                    break;
                case FRAGMENT_ECG:
                    Log.i(TAG, "startTransaction: ecg");
                    fragment = new EcgFragment();
                    break;
            }
            addFragmentTag(fragmentTransaction, fragmentId, fragment);
        }
        fragmentTransaction.commitAllowingStateLoss();
        selectedFragmentId=fragmentId;
    }

    private void addFragmentTag(FragmentTransaction fragmentTransaction, int tag, Fragment fragment) {
        fragmentList.add(fragment);
        fragmentTransaction.add(R.id.frameLayout_content, fragment, String.valueOf(tag));
    }

    private void hideFragment(FragmentTransaction fragmentTransaction) {
        for (Fragment fragment : fragmentList) {
            fragmentTransaction.hide(fragment);
        }
    }

    private Fragment findFragment(int tag) {

        for (Fragment fragment : fragmentList) {
            String fragmentTag=fragment.getTag();
       //     Log.i(TAG, "findFragment: "+fragmentTag);
            if(TextUtils.isEmpty(fragmentTag))return null;
            if (fragmentTag.equals(String.valueOf(tag))) return fragment;
        }
        return null;
    }
    String deviceType = JstyleDevice.device_1755;


/*
    private void showHealthFragment(FragmentTransaction fragmentTransaction) {
        if (deviceType.equals(JstyleDevice.device_1755)) {
            if (healthFragment == null) {
                healthFragment = new HealthFragment();
                fragmentTransaction.add(R.id.frameLayout_content, healthFragment);
            } else {
                fragmentTransaction.show(healthFragment);
            }
        } else if(deviceType.equals(JstyleDevice.device_1790_01)){
            if (ecgHistoryFragment == null) {
                ecgHistoryFragment = new EcgHistoryFragment();
                fragmentTransaction.add(R.id.frameLayout_content, ecgHistoryFragment);
            } else {
                fragmentTransaction.show(ecgHistoryFragment);
            }
        }else if(deviceType.equals(JstyleDevice.device_1810)){
            if (heart1810Fragment == null) {
                heart1810Fragment = new Heart1810Fragment();
                fragmentTransaction.add(R.id.frameLayout_content, heart1810Fragment);
            } else {
                fragmentTransaction.show(heart1810Fragment);
            }
        }

    }
*/
    private int getFragmentHealthId(){
        int id=FRAGMENT_HEALTH;
        JstyleDevice jstyleDevice=MyApplication.getJstyleDevice();
         if(jstyleDevice instanceof Device1790){
           id=FRAGMENT_HEALTH1790;
        }else if(jstyleDevice instanceof Device1810){
           id=FRAGMENT_HEALTH1810;
        }
        return id;
    }

//    private void hideFragment(FragmentTransaction fragmentTransaction) {
//        hideFragment(homePageFragment, fragmentTransaction);
//        hideFragment(healthFragment, fragmentTransaction);
//        hideFragment(exerciseFragment, fragmentTransaction);
//        hideFragment(settingFragment, fragmentTransaction);
//        hideFragment(ecgHistoryFragment, fragmentTransaction);
//        hideFragment(ecgFragment, fragmentTransaction);
//        hideFragment(heart1810Fragment, fragmentTransaction);
//    }

    private void hideFragment(Fragment fragment, FragmentTransaction transaction) {
        if (fragment != null) {
            transaction.hide(fragment);
        }
    }

    public static int phoneDataLength = 200;//手机一个包能发送的最多数据
    private static final String TAG = "MainActivity";

    @OnClick(R.id.iv_more)
    public void onViewClicked() {
        if (MyApplication.getJstyleDevice() instanceof Device1790 ){
            RadioGroupHome.clearCheck();
            startTransaction(FRAGMENT_ECG);
        }
    }
    public static boolean enterEcg;
    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState) {
            case EnterEcg:
                RxBus rxBus=RxBus.getInstance();
                BleData bleData=new BleData();
                bleData.setAction(action_enterecg);
                rxBus.post(bleData);
                enterEcg=true;
                RadioGroupHome.clearCheck();;
                startTransaction(FRAGMENT_ECG);
                EcgFragment ecgFragment= (EcgFragment) findFragment(FRAGMENT_ECG);
                if(ecgFragment!=null)ecgFragment.changeChartVisibility(true);

                break;
            case GET_GOAL:
                int stepGoal = Integer.parseInt(maps.get(DeviceKey.KStepGoal));
                SharedPreferenceUtils.setSpInteger(SharedPreferenceUtils.KEY_Step_goal, stepGoal);

                break;
            case Set_EXERCISE_MODE:
//                String enable=maps.get(DeviceKey.KEnable_exercise);
//                if(exerciseFragment!=null)exerciseFragment.enableExercise(enable);
                break;
            case SET_STEP_MODEL:
                 homePageFragment= (HomePageFragment) findFragment(FRAGMENT_HOME);
                 heart1810Fragment= (Heart1810Fragment) findFragment(FRAGMENT_HEALTH1810);
                if (homePageFragment!=null) homePageFragment.updateActivityData(maps);
                if(heart1810Fragment!=null)heart1810Fragment.updateHeartData(maps);
                break;
            case SEND_DEVICE_Time:
                isSyc=true;
               // phoneDataLength = Integer.parseInt(maps.get(DeviceKey.KPhoneDataLength));
                lastDetailTime = StepDetailDataDaoManager.getLastInsertDataTime();
                lastSleepTime = SleepDataDaoManager.getLastInsertDataTime();
                if (gpsSendTime) {
                    gpsSendTime = false;
                    return;
                }
                offerData(SendCmdState.READ_DEVICE_BATTERY);
                offerData();

                break;
            case READ_DEVICE_BATTERY:
                String battery = maps.get(DeviceKey.KBattery);
                batteryValue=Integer.valueOf(battery);
                String showBattery = battery + " %";
                checkBattery(Integer.valueOf(battery));
                if(isSyc){
                    homePageFragment= (HomePageFragment) findFragment(FRAGMENT_HOME);
                    if (homePageFragment != null) homePageFragment.startSycData();
                }
                settingFragment=(SettingFragment)findFragment(FRAGMENT_SETTING);
                if (settingFragment != null) settingFragment.updateBattery(showBattery);
                break;
            case READ_VERSION:
                String version = maps.get(DeviceKey.KVersion);
                queryVersion(version);
                break;
            case GET_DEVICE_Time:
                String gpsDate = maps.get(DeviceKey.KGpsTime);
                String timeZone = maps.get(DeviceKey.KTimeZone);
                phoneDataLength = Integer.parseInt(maps.get(DeviceKey.KPhoneDataLength));
             //   Log.i(TAG, "dataCallback: " + phoneDataLength);
                JstyleDevice jstyleDevice=MyApplication.getJstyleDevice();
                ResolveUtil.hrvLength =jstyleDevice.getHrvLength();
                ResolveUtil.activityLength =jstyleDevice.getActivityLength();

                    sendTime();


                break;
            case CHECK_RESUPDATE:
                int position0 = Integer.parseInt(maps.get(DeviceKey.KGpsResCheck0));
                int position1 = Integer.parseInt(maps.get(DeviceKey.KGpsResCheck1));
              //  startActivity(ResUpdateActivity.class);

                if (position0 == 1) {
                    if (position1 == 1) {//需要升级
                        startActivity(ResUpdateActivity.class);
                    } else {
                        enableActivityData(true);
                    }
                }
                break;
            case Function:
                String findPhone = maps.get(DeviceKey.KFunction_FindPhone);
                String endTel = maps.get(DeviceKey.KFunction_reject_tel);
                String Tel = maps.get(DeviceKey.KFunction_tel);
                if (findPhone != null) {
                    startPlayMusic();
                } else if (!TextUtils.isEmpty(endTel)) {
                    rejectPhone();
                } else if (!TextUtils.isEmpty(Tel)) {
                    answerPhone();
                }
                break;
            case Sos:
                initLocation();
                break;
        }

    }
    private void queryVersion(final String version) {
        Log.i(TAG, "queryVersion: " + version);
        String versionCode = version.replace(".", "");
        Map<String, String> queryVersion = new HashMap<>();
       queryVersion.put(NetWorkConast.KEY_DEVICE_VERSION, versionCode);
       //  queryVersion.put(NetWorkConast.KEY_DEVICE_VERSION, "066");
        queryVersion.put(NetWorkConast.KEY_type, MyApplication.getJstyleDevice().getUpdateNo());
        NetWorkUtil.getInstance().getJstyleApi().queryDeviceVersion(queryVersion).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<UpdateData>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(UpdateData value) {
                disMissProgressDialog();
                int code = value.getMsgCode();
                SettingFragment settingFragment=(SettingFragment)findFragment(FRAGMENT_SETTING);
                if (code == GlobalConast.VALUE_NEED_UPDATE) {
                    String updateFilePath = value.getData().getUrl();
                    String deviceVersion = value.getData().getVersion();
                    if (settingFragment != null) {
                        settingFragment.changeUpdateStatus(true);
                        settingFragment.updateVersion(updateFilePath,deviceVersion);
                    }
                    if(!isSyc)return;
                    showUpdateDialog(updateFilePath,deviceVersion);
                }else{
                    if (settingFragment != null) settingFragment.changeUpdateStatus(false);
                    if(!isSyc)return;
                    checkUpdateFile();
                }

            }

            @Override
            public void onError(Throwable e) {
                disMissProgressDialog();
                checkUpdateFile();
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }
    private void showUpdateDialog(final String filePath,String deviceVersion) {
        Intent intent=new Intent(this,FileUpdateActivity.class);
        intent.putExtra(FileUpdateActivity.key_url,filePath);
        intent.putExtra(FileUpdateActivity.key_version,deviceVersion);
        intent.putExtra(FileUpdateActivity.key_battery,batteryValue);
        startActivity(intent);

    }
    private void sendSos(double lat,double lng) {
        String uid=NetWorkUtil.getUserId();
        NetWorkUtil.getInstance().getJstyleApi().sendSos(uid,String.valueOf(lat),String.valueOf(lng)).compose(SchedulersTransformer.<SosContact>io2MainObservable()).subscribe(new Observer<SosContact>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(SosContact sosContact) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void rejectPhone() {
        Method method = null;
        try {
            method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
            IBinder binder = (IBinder) method.invoke(null, new Object[]{Context.TELEPHONY_SERVICE});
            ITelephony telephony = ITelephony.Stub.asInterface(binder);
            try {
                telephony.endCall();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    private void answerPhone() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            TelecomManager telecomManager =
                    (TelecomManager) getSystemService(TELECOM_SERVICE);
            Method method = null;
            try {
                method = Class.forName("android.telecom.TelecomManager").getMethod("acceptRingingCall");
                method.invoke(telecomManager);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            long eventTime = SystemClock.uptimeMillis() - 1;
        //    Log.i(TAG, "dataCallback: " + eventTime);
            KeyEvent eventDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK);
            KeyEvent eventUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //    Log.i(TAG, "dataCallback: 接听");
                audioManager.dispatchMediaKeyEvent(eventDown);
                audioManager.dispatchMediaKeyEvent(eventUp);
            } else {
                try {
                    Runtime.getRuntime().exec("input keyevent " + Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void startPlayMusic() {
        boolean isEnable = checkDialogPermission();
        if (!isEnable) return;
        boolean findPhone = SharedPreferenceUtils.getBoolean(GlobalConst.KEY_Find_Phone, true);
        if (!findPhone) return;
        startCountDownTimer();
        if (ringAlertDialog != null && ringAlertDialog.isShowing()) return;
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        ringtone = RingtoneManager.getRingtone(this, notification);
        ringtone.play();
        vibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);
        vibrator.vibrate(new long[]{200, 300, 300}, 0);
        ringAlertDialog = new AlertDialog.Builder(this)
                .setMessage(getString(R.string.Find_Phone))
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        unSubscribe(disposableFindPhone);
                        stopPlayMusic();
                        sendData(SendCmdState.Back_HOME);
                    }
                }).create();
        if (Build.VERSION.SDK_INT >= 26) {//8.0新特性
            ringAlertDialog.getWindow().setType(
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
        } else {
            ringAlertDialog.getWindow().setType(
                    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        }
        ringAlertDialog.setCancelable(false);
        ringAlertDialog.show();
    }

    Disposable disposableFindPhone;
    long findPhoneTime = 0;

    private void startCountDownTimer() {
        findPhoneTime = System.currentTimeMillis();
        if (disposableFindPhone != null && !disposableFindPhone.isDisposed()) return;
        Observable.interval(1, TimeUnit.SECONDS)
                .compose(SchedulersTransformer.<Long>io2MainObservable()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableFindPhone = d;
            }

            @Override
            public void onNext(Long aLong) {
                if (System.currentTimeMillis() - findPhoneTime >= 2000) {
                    if (ringAlertDialog != null && ringAlertDialog.isShowing())
                        ringAlertDialog.dismiss();
                    stopPlayMusic();
                    disposableFindPhone.dispose();
                }
                Log.i(TAG, "onNext: " + aLong);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void stopPlayMusic() {
        if (ringtone != null && ringtone.isPlaying()) ringtone.stop();
        if (vibrator != null) vibrator.cancel();
    }

    private android.support.v7.app.AlertDialog gpsDialog;

    private void checkGpsUpdate(String gpsDate) {
        long time = DateUtil.getDateLong(gpsDate);
        long nowTime = System.currentTimeMillis();
        long durtaion = nowTime - time;
        if (durtaion > 6 * 24 * 60 * 60 * 1000l) {//大于6天需要升级
            if (gpsDialog == null) {
                gpsDialog = new AlertDialog.Builder(this,R.style.appalertdialog)
                        .setMessage(R.string.Find_New_gps_version)
                        .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                checkStoragePermissions(NetWorkUtil.downloadUrl);
                            }
                        })
                        .setNegativeButton(getString(R.string.later), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                sendTime();
                            }
                        })
                        .create();
            }
            if (!gpsDialog.isShowing()) gpsDialog.show();
        } else {
            sendTime();
        }
    }

    private boolean gpsSendTime;
    long gpsFileLength = 0;

    private void checkStoragePermissions(final String path) {
        PermissionsUtil.requestPermissions(this, new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                downLoadUpdatePath(path);
            }

            @Override
            public void NeverAskAgain() {

            }

            @Override
            public void disallow(String name) {
                sendTime();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    private void downLoadUpdatePath(final String filePath) {
        //sendTime();
        //gpsSendTime=true;
        if (!NetWorkUtil.isNetworkConnected(this)) {
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        String[] filePaths = filePath.split("/");
        final String lastPath = filePaths[filePaths.length - 1];
        // showProgressDialog(getString(R.string.Downloading_the_new_firmware));
        NetWorkUtil.getInstance()
                .getJstyleApi()
                .downloadPath(filePath)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .doOnNext(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        gpsFileLength = responseBody.contentLength();
                        try {
                            writeToDisk(lastPath, responseBody);
                        } catch (IOException e) {
                            throw new NetWorkException(e.getMessage());
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ResponseBody value) {
                Log.i(TAG, "onNext: ");

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
                disMissProgressDialog();
                ScreenUtils.showSetSuccessFul(frameLayoutContent, getString(R.string.network_bad));
                sendTime();
            }

            @Override
            public void onComplete() {
                if (gpsFileLength == 0) {
                    ScreenUtils.showSetSuccessFul(frameLayoutContent, getString(R.string.network_bad));
                    sendTime();
                } else {
                    startActivity(GpsUpdateActivity.class, "gpsFile", lastPath);

                }
            }
        });
    }

    private void writeToDisk(final String filePath, ResponseBody responseBody) throws IOException {
        String rootPath = ImageUtils.UPDATEPATH;
        File file = new File(rootPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File fileMusic = new File(rootPath, filePath);
        //if (fileMusic.exists() && fileMusic.length() == responseBody.contentLength()) return;
        byte[] buffer = new byte[1024 * 8];
        int len;
        FileOutputStream out = new FileOutputStream(fileMusic);
        InputStream in = responseBody.byteStream();
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        in.close();


    }

    int detailCount = 0;
    int sleepCount = 0;
    int heartCount = 0;

    @Override
    public void dataCallback(DeviceBean deviceBean, SendCmdState sendCmdState) {
        super.dataCallback(deviceBean, sendCmdState);
        switch (sendCmdState) {
            case GET_STEP_DATA:
                boolean isFinish = deviceBean.isFinish();
                list.addAll(deviceBean.getDataList());
                if (isFinish) {
                    getDetailData(0);
                    saveStepData();
                }
                break;
            case GET_STEP_DETAIL:
                boolean isDetailFinish = deviceBean.isFinish();
                listDetail.addAll(deviceBean.getDataList());
                detailCount++;
              //  Log.i(TAG, "dataCallback: "+detailCount);
                if (isDetailFinish) {
                    detailCount = 0;
                    getSleepData(0);
                    saveStepDetailData();
                } else {
                    if (detailCount == 50) {
                        detailCount = 0;
                        Map<String, String> map = deviceBean.getDataList().get(0);
                        String date = map.get(DeviceKey.KDetailStepDate);
                        isDetailBefore = TextUtils.isEmpty(lastDetailTime) ? true : DateUtil.beforeData(lastDetailTime, date);
                        if (isDetailBefore) {
                            getDetailData(2);
                        } else {
                            getSleepData(0);
                            saveStepDetailData();

                        }

                    }
                }
                break;
            case GET_SLEEP_DETAIL:
                boolean isSleepFinish = deviceBean.isFinish();
                listSleep.addAll(deviceBean.getDataList());
                sleepCount++;
                if (isSleepFinish) {
                    sleepCount = 0;
                    getOnceHeartData(0);
                    saveSleepData();
                } else {
                    if (sleepCount == 50) {
                        sleepCount = 0;
                        Map<String, String> map = deviceBean.getDataList().get(0);
                        String date = map.get(DeviceKey.KSleepDate);
                        isSleepBefore = TextUtils.isEmpty(lastSleepTime) ? true : DateUtil.beforeData(lastDetailTime, date);
                        if (isSleepBefore) {
                            getSleepData(2);
                        } else {
                            getOnceHeartData(0);
                            saveSleepData();
                        }
                    }
                }
                break;
            case GET_ONCE_HEARTDATA:
                boolean isHeartFinish = deviceBean.isFinish();
                listHeart.addAll(deviceBean.getDataList());
                heartCount++;
                if (isHeartFinish) {
                    heartCount = 0;
                    getHeartHistoryData(0);
                    saveHeartData();
                } else {
                    if (heartCount == 50) {
                        heartCount = 0;
                        getOnceHeartData(2);
                    }
                }
                break;
            case GET_HEART_DATA:
                boolean isHeartHistoryFinish = deviceBean.isFinish();
                listHistoryHeart.addAll(deviceBean.getDataList());
                heartCount++;
                if (isHeartHistoryFinish) {
                    heartCount = 0;
                    getHrvData();
                    saveHeartHistoryData();
                } else {
                    if (heartCount == 50) {
                        heartCount = 0;
                        getHeartHistoryData(2);
                    }
                }

                break;
            case GET_HRV_DATA:
                boolean isHrvFinish = deviceBean.isFinish();
                listHrv.addAll(deviceBean.getDataList());
                if (isHrvFinish) {
                    sendData(SendCmdState.READ_VERSION);
                    saveHealthHistoryData();
                }
                break;

        }
    }

    private void getDeviceTime() {//
        Observable.timer(MyApplication.getJstyleDevice().getDeviceNo().equals(JstyleDevice.device_1755)?0:600,TimeUnit.MILLISECONDS).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long aLong) {
                sendData(SendCmdState.GET_DEVICE_Time);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    private void saveHeartHistoryData() {
        final List<HeartData> heartDataList = new ArrayList<>();
        UploadData uploadData = UploadUtils.getUploadData(deviceAddress, NetWorkConast.dynamicHeartRateData);
        List<UploadData.DataTotalBean> dataList = new ArrayList<>();
        uploadData.setDataTotal(dataList);
        for (Map<String, String> map : listHistoryHeart) {
            UploadData.DataTotalBean dataTotalBean = new UploadData.DataTotalBean();
            List<String> listHealth = new ArrayList<>();
            String date = map.get(DeviceKey.KHeartDate);
            String hrString = map.get(DeviceKey.KHeartData);
            String[] hrArray = hrString.split(" ");
            // Log.i(TAG, "saveHeartHistoryData: "+date+" "+hrString);
            long startL = DateUtil.getGpsDateLong(date);
            for (int i = 0; i < hrArray.length; i++) {
                int hr = Integer.valueOf(hrArray[i]);
                long endL = startL + i * 1000 * 60l;
                String endTime = DateUtil.getFormatTimeString(endL);
                if (hr != 0) {
                    HeartData heartData = new HeartData();
                    heartData.setAddress(deviceAddress);
                    heartData.setHeart(hr);
                    heartData.setTime(endTime);
                    heartDataList.add(heartData);
                    listHealth.add(String.valueOf(hr));
                }
                //   Log.i(TAG, "saveHeartHistoryData:2 "+endTime);
            }
            dataTotalBean.setTime("20" + date);
            dataTotalBean.setDataDetail(listHealth);
            dataList.add(dataTotalBean);
        }
        UploadUtils.uploadData(uploadData);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                HeartDataDaoManager.insertData(heartDataList);
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                listHeart.clear();

                //  if (homePageFragment != null) homePageFragment.saveFinish();

            }
        });
    }

    private void saveHealthHistoryData() {
        deviceAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        final List<HealthData> healthDataList = new ArrayList<>();
        List<HealthData> healthDataAll = HealthDataDaoManager.queryAllData();
//        List<String> list = new ArrayList<>();
//        for (HealthData healthDataD : healthDataAll) {
//            list.add(healthDataD.getTime());
//        }
        UploadData uploadData = UploadUtils.getUploadData(deviceAddress, NetWorkConast.hrvData);
        List<UploadData.DataTotalBean> dataList = new ArrayList<>();
        uploadData.setDataTotal(dataList);
        for (Map<String, String> map : listHrv) {
            UploadData.DataTotalBean dataTotalBean = new UploadData.DataTotalBean();
            List<String> listHealth = new ArrayList<>();
            String date = map.get(DeviceKey.KHrvDate);
          //  if (list.contains(date)) continue;
            String hrv = map.get(DeviceKey.KHrvValue);
            String blood = map.get(DeviceKey.KHrvBloodValue);
            String heart = map.get(DeviceKey.KHrvHeartValue);
            String tired = map.get(DeviceKey.KHrvTired);
            String highBloodPressure = map.get(DeviceKey.KHrvBloodHighPressure);
            String lowBloodPressure = map.get(DeviceKey.KHrvBloodLowPressure);
            String moodValue = map.get(DeviceKey.KHrvMoodValue);
            String breathRate = map.get(DeviceKey.KHrvBreathRate);
            HealthData healthData = new HealthData();
            healthData.setAddress(deviceAddress);
            healthData.setTime(date);
            healthData.setHrv(Integer.valueOf(hrv));
            healthData.setHighBloodPressure(Integer.valueOf(highBloodPressure));
            healthData.setLowBloodPressure(Integer.valueOf(lowBloodPressure));
            healthData.setPressure(Integer.valueOf(tired));
            healthData.setHeartRate(Integer.valueOf(heart));
            healthData.setBloodValue(Integer.valueOf(blood));
            if (!TextUtils.isEmpty(moodValue)) healthData.setMoodValue(Integer.valueOf(moodValue));
            if (!TextUtils.isEmpty(breathRate))
                healthData.setBreathValue(Integer.valueOf(breathRate));
            healthDataList.add(healthData);

            listHealth.add(hrv);
            listHealth.add(blood);
            listHealth.add(heart);
            listHealth.add(tired);
            listHealth.add(highBloodPressure);
            listHealth.add(lowBloodPressure);
            dataTotalBean.setTime("20" + date);
            dataTotalBean.setDataDetail(listHealth);
            dataList.add(dataTotalBean);
        }
        UploadUtils.uploadData(uploadData);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                HealthDataDaoManager.insertData(healthDataList);
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                listHeart.clear();
                HomePageFragment homePageFragment = (HomePageFragment) findFragment(FRAGMENT_HOME);
                if (homePageFragment != null) homePageFragment.saveFinish();

            }
        });
    }

    private void saveHeartData() {
        final List<HeartData> heartDataList = new ArrayList<>();
        deviceAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        UploadData uploadData = UploadUtils.getUploadData(deviceAddress, NetWorkConast.staticHeartRateData);
        List<UploadData.DataTotalBean> dataList = new ArrayList<>();
        uploadData.setDataTotal(dataList);
        for (Map<String, String> map : listHeart) {
            UploadData.DataTotalBean dataTotalBean = new UploadData.DataTotalBean();
            List<String> listHealth = new ArrayList<>();
            String date = map.get(DeviceKey.KOnceHeartDate);
            int heartRate = Integer.parseInt(map.get(DeviceKey.KOnceHeartValue));
            if (heartRate != 0) {
                HeartData heartData = new HeartData();
                heartData.setAddress(deviceAddress);
                heartData.setHeart(heartRate);
                heartData.setTime(date);
                heartDataList.add(heartData);
                listHealth.add(String.valueOf(heartRate));
                dataTotalBean.setTime("20" + date);
                dataTotalBean.setDataDetail(listHealth);
                dataList.add(dataTotalBean);
            }
        }
        UploadUtils.uploadData(uploadData);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                HeartDataDaoManager.insertData(heartDataList);
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                listHeart.clear();
                // if (homePageFragment != null) homePageFragment.saveFinish();

            }
        });
    }

    private void saveSleepData() {
        deviceAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        UploadData uploadData = UploadUtils.getUploadData(deviceAddress, NetWorkConast.detailSleepData);
        List<UploadData.DataTotalBean> dataList = new ArrayList<>();
        uploadData.setDataTotal(dataList);
        final List<SleepData> sleepDataList = new ArrayList<>();
        for (Map<String, String> map : listSleep) {
            UploadData.DataTotalBean dataTotalBean = new UploadData.DataTotalBean();
            List<String> listHealth = new ArrayList<>();
            String time = map.get(DeviceKey.KSleepDate);
            long startMil = DateUtil.getDefaultLongMi(time);
            String[] sleepQuantity = map.get(DeviceKey.KSleepQuantity).split(" ");
            for (int i = 0; i < sleepQuantity.length; i++) {
                SleepData sleepData = new SleepData();
                sleepData.setAddress(deviceAddress);
                sleepData.setDateString(sleepQuantity[i]);
                long timeMil = startMil + 5 * 60 * 1000l * i;
                sleepData.setTime(DateUtil.getFormatTimeString(timeMil));
                sleepDataList.add(sleepData);
                listHealth.add(sleepQuantity[i]);
            }
            dataTotalBean.setTime("20" + time);
            dataTotalBean.setDataDetail(listHealth);
            dataList.add(dataTotalBean);
        }
        UploadUtils.uploadData(uploadData);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                SleepDataDaoManager.insertData(sleepDataList);
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                listSleep.clear();
                // if (homePageFragment != null) homePageFragment.saveFinish();

            }
        });

    }

    /**
     * 实时计步
     *
     * @param enable
     */
    private void enableActivityData(boolean enable) {
        if(isSyc){
            SetPersonalInfo setPersonalInfo=updateDeviceUserInfo();
            if(setPersonalInfo!=null)offerData(SendCmdState.SET_PERSONAL_INFO, setPersonalInfo);
        }
        if(enable)isSyc=false;
        StepModel stepModel = new StepModel();
        stepModel.setStepState(enable);
        offerData(SendCmdState.GET_GOAL);
        offerData(SendCmdState.SET_STEP_MODEL, stepModel);
        offerData();
    }

    private void getDetailData(int count) {
        GetData getData = new GetData();
        getData.setDataNum(count);
        sendData(SendCmdState.GET_STEP_DETAIL, getData);
    }

    private void getSleepData(int count) {
        GetData getData = new GetData();
        getData.setDataNum(count);
        sendData(SendCmdState.GET_SLEEP_DETAIL, getData);
    }

    private void getOnceHeartData(int count) {
        GetData getData = new GetData();
        getData.setDataNum(count);
        sendData(SendCmdState.GET_ONCE_HEARTDATA, getData);
    }

    private void getHeartHistoryData(int count) {
        GetData getData = new GetData();
        getData.setDataNum(count);
        sendData(SendCmdState.GET_HEART_DATA, getData);
    }

    private void getHrvData() {
        GetData getData = new GetData();
        sendData(SendCmdState.GET_HRV_DATA, getData);
    }

    /**
     * 运动总数据
     */
    private void saveStepData() {
        final List<StepData> stepDataList = new ArrayList<>();
        deviceAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        UploadData uploadData = UploadUtils.getUploadData(deviceAddress, NetWorkConast.totalSportData);
        List<UploadData.DataTotalBean> dataList = new ArrayList<>();
        uploadData.setDataTotal(dataList);
        for (Map<String, String> map : list) {
            StepData stepData = new StepData();

            stepData.setAddress(deviceAddress);
            String time = map.get(DeviceKey.KHistorySportTime);
            String totalStep = map.get(DeviceKey.KHistorySteps);
            String distance = map.get(DeviceKey.KHistoryDistance);
            String cal = map.get(DeviceKey.KHistoryCalories);
            String goal = map.get(DeviceKey.KHistoryGoal);
            String date = map.get(DeviceKey.KHistoryDate);
          //  Log.i(TAG, "saveStepData: " + date + " " + totalStep);
            String exerciseTime = map.get(DeviceKey.KHistoryExerciseTime);
            stepData.setDate(date);
            stepData.setTime(time);
            stepData.setStep(totalStep);
            stepData.setDistance(distance);
            stepData.setCal(cal);
            stepData.setGoal(goal);
            stepData.setExerciseTime(exerciseTime);
            stepDataList.add(stepData);
            List<String> listStep = new ArrayList<>();
            listStep.add(totalStep);
            listStep.add(time);
            listStep.add(distance);
            listStep.add(cal);
            listStep.add(goal);
            listStep.add(exerciseTime);
            UploadData.DataTotalBean dataTotalBean = new UploadData.DataTotalBean();
            dataTotalBean.setTime("20" + date);
            dataTotalBean.setDataDetail(listStep);
            dataList.add(dataTotalBean);
        }
        UploadUtils.uploadData(uploadData);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                StepDataDaoManager.insertData(stepDataList);
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                list.clear();
            }
        });

    }

    /**
     * 运动详细数据
     */
    private void saveStepDetailData() {
        final List<StepDetailData> stepDataList = new ArrayList<>();
        deviceAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        UploadData uploadData = UploadUtils.getUploadData(deviceAddress, NetWorkConast.detailSportData);
        List<UploadData.DataTotalBean> dataList = new ArrayList<>();
        uploadData.setDataTotal(dataList);
        for (Map<String, String> map : listDetail) {
            UploadData.DataTotalBean dataTotalBean = new UploadData.DataTotalBean();
            List<String> list = new ArrayList<>();
            StepDetailData stepData = new StepDetailData();
            stepData.setAddress(deviceAddress);
            String date = map.get(DeviceKey.KDetailStepDate);
            String totalStep = map.get(DeviceKey.KDetailSteps);
            String distance = map.get(DeviceKey.KDetailDistance);
            String cal = map.get(DeviceKey.KDetailCalories);
            String detailStep = map.get(DeviceKey.KDetailMinterStep);
            String[] stepArrays = detailStep.split(" ");
            for (String step : stepArrays) {
                list.add(step);
            }
            stepData.setDate(date);
            stepData.setStep(totalStep);
            stepData.setDistance(distance);
            stepData.setCal(cal);
            stepData.setMinterStep(detailStep);
            stepDataList.add(stepData);
            dataTotalBean.setTime("20" + date);
            dataTotalBean.setDataDetail(list);
            dataList.add(dataTotalBean);
        }
        UploadUtils.uploadData(uploadData);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                StepDetailDataDaoManager.insertData(stepDataList);
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                listDetail.clear();
              //  UploadUtils.createDataForRequest(MainActivity.this);
                //if (homePageFragment != null) homePageFragment.saveFinish();

            }
        });

    }

    private void Connect() {
        String dfuAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_DFU_ADDRESS);
        if (!TextUtils.isEmpty(dfuAddress)) {
            showContinueDfuDialog();
            return;
        }
        final String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        if (TextUtils.isEmpty(address)) {
            showToast(getString(R.string.not_pair_device));
            return;
        }
        if(isBleEnable()){
            if (!BleManager.getInstance().isConnected()) {
                startConnect(address);
            } else {
                getDeviceTime();
            }
        }

    }

    private void showContinueDfuDialog() {
        TipsDialog tipsDialog=new TipsDialog(this,R.style.jstyleDialog_style);
       tipsDialog.setTitle(getString(R.string.Caution));
        tipsDialog.setContent(getString(R.string.dfu_continue_content));
        tipsDialog.setConfimText(getString(R.string.ok));
        tipsDialog.setTipsConfimListener(new TipsDialog.TipsConfimListener() {
            @Override
            public void onConfim() {
                enterOta();
            }
        }).setTipsCancelListener(new TipsDialog.TipsCancelListener() {
            @Override
            public void onCancel() {
                SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_DFU_ADDRESS,"");
                final String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
                if (TextUtils.isEmpty(address)) {
                    showToast(getString(R.string.not_pair_device));
                    return;
                }
                if(isBleEnable()){
                    if (!BleManager.getInstance().isConnected()) {
                        startConnect(address);
                    } else {
                        getDeviceTime();
                    }
                }
            }
        });

        tipsDialog.show();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        Log.i(TAG, "onSaveInstanceState: ");
    }

    long checkAppTime;

    private void checkAppVersion() {
        if (System.currentTimeMillis() - checkAppTime < 24 * 60 * 60 * 1000) return;
        AppUpdateUtils.queryAppVersion(this);
        checkAppTime = System.currentTimeMillis();
    }

    private void startConnect(final String address) {
        long delay = isNeedDelay ? 1500 : 0;
        showProgressDialog(getString(R.string.connectting));
        Observable.timer(delay, TimeUnit.MILLISECONDS).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long value) {
                isNeedDelay = false;
                //  isFirstConnect=true;
                BleManager.getInstance().connectDevice(address);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });


    }

    @Override
    protected void changeDevice() {
        super.changeDevice();
        HomePageFragment homePageFragment= (HomePageFragment) findFragment(FRAGMENT_HOME);
        if (homePageFragment != null) homePageFragment.changeDevice();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  unregisterReceiver(receiver);
        unSubscribe(disposableFindPhone);

        unregisterReceiver(receiver);
      //  BleManager.getInstance().unbindService();
        stopPlayMusic();

    }

    @Override
    protected void onConnect() {
        super.onConnect();
        disMissProgressDialog();
        otaSuccessGetDeviceTime();
        HomePageFragment homePageFragment= (HomePageFragment) findFragment(FRAGMENT_HOME);
        if (homePageFragment != null) homePageFragment.updateConnectStatus(true);
    }

    @Override
    protected void onDisconnect() {
        super.onDisconnect();
        disMissProgressDialog();
        disMissDialog(gpsDialog);
        if(batteryDialog!=null)batteryDialog.dismiss();
        clearData();
        HomePageFragment homePageFragment= (HomePageFragment) findFragment(FRAGMENT_HOME);
        EcgFragment ecgFragment= (EcgFragment) findFragment(FRAGMENT_ECG);
        SettingFragment settingFragment= (SettingFragment) findFragment(FRAGMENT_SETTING);
        Heart1810Fragment heart1810Fragment= (Heart1810Fragment) findFragment(FRAGMENT_HEALTH1810);
        if (homePageFragment != null) homePageFragment.updateConnectStatus(false);
        if(ecgFragment!=null)ecgFragment.changeChartVisibility(false);
        if(settingFragment!=null)settingFragment.changeUpdateStatus(false);
        if(heart1810Fragment!=null)heart1810Fragment.onDisconnect();
    }

    private void clearData() {
       list.clear();
       listDetail.clear();
       listSleep.clear();
       listHeart.clear();
       listHistoryHeart .clear();
       listHrv .clear();
       detailCount=0;
       sleepCount=0;
       heartCount=0;
    }

    @Override
    protected void startOta() {
        super.startOta();
        enterOta();
    }

    boolean isOtaSuccess;

    @Override
    protected void otaSuccess() {
        super.otaSuccess();
        ScreenUtils.showSetSuccessFul(RadioGroupHome, getString(R.string.Update_success));
        isOtaSuccess = true;
        final String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        BleManager.getInstance().connectDevice(address,true);
    }

    private void otaSuccessGetDeviceTime() {
        //升级后手环需要几秒时间去读取gps最后更新时间
        long delay = isOtaSuccess ? 3 : 0;
        Observable.timer(delay, TimeUnit.SECONDS).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                Log.i(TAG, "onComplete: ");
                isOtaSuccess = false;
                getDeviceTime();
            }
        });
    }

    @Override
    protected void otaFailed() {
        super.otaFailed();
        showOtaSuccess(false);
    }


    @Override
    protected void changeGoal() {
        super.changeGoal();
        HomePageFragment homePageFragment=(HomePageFragment)findFragment(FRAGMENT_HOME);
        if (homePageFragment != null) homePageFragment.updateGoal();

    }

    private void checkUpdateFile() {//检查是否需要资源升级

        final String path = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_RES_FILEPATH);
        Log.i(TAG, "checkUpdateFile: " + path);
        JstyleDevice jstyleDevice=MyApplication.getJstyleDevice();
        if (jstyleDevice instanceof Device1810 ||TextUtils.isEmpty(path)) {
            enableActivityData(true);
            return;
        }
        PermissionsUtil.requestPermissions(this, new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                startCheckFile(path);
            }

            @Override
            public void NeverAskAgain() {

            }

            @Override
            public void disallow(String name) {
                enableActivityData(true);
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }

    @Override
    protected void dfuLater() {
        super.dfuLater();
        checkUpdateFile();
        // if (homePageFragment != null) homePageFragment.dfuLater();
    }
    private void startCheckFile(String path) {
        File binFile = new File(path + "color565.bin");
        if (!binFile.exists()) {
            enableActivityData(true);
            return;
        }
        byte[] binByte = ZipUtils.readFile(binFile);
        String md5String = ZipUtils.loadFromSDFile(path + "color565MD5.txt");
        if(TextUtils.isEmpty(md5String)){
            enableActivityData(true);
            return;
        }
        byte[] binMd5 = ZipUtils.getMd5Byte(md5String.trim());
        int length = binByte.length;
        int crc16 = ResolveData.CalcCRC16(binByte, binByte.length);
        byte[] value = new byte[26];
        value[0] = DeviceConst.cmdCheck;
        value[1] = 01;
        value[2] = (byte) ((length) & 0xff);//低位在前
        value[3] = (byte) ((length >> 8) & 0xff);
        value[4] = (byte) ((length >> 16) & 0xff);
        value[5] = (byte) ((length >> 24) & 0xff);
        System.arraycopy(binMd5, 0, value, 6, binMd5.length);
        value[22] = (byte) ((crc16) & 0xff);
        value[23] = (byte) ((crc16 >> 8) & 0xff);
        int crcValue16 = ResolveData.CalcCRC16(value, 24);
        value[24] = (byte) ((crcValue16) & 0xff);
        value[25] = (byte) ((crcValue16 >> 8) & 0xff);
        BleManager.getInstance().writeValue(value);
    }

    public void showOtaSuccess(boolean successFul) {
        String info = successFul ? getString(R.string.Update_success) : getString(R.string.Updated_failed);
        if (successFul && settingFragment != null) settingFragment.changeUpdateStatus(false);
        AlertDialog alertDialog = new AlertDialog.Builder(this, R.style.appalertdialog)
                .setTitle(getString(R.string.Firmware_Update))
                .setMessage(info)
                .setCancelable(false)
                .setPositiveButton(getString(R.string.Confirm), null)
                .create();
        alertDialog.show();
    }

    long batteryAlertTime = 0;

    private void checkBattery(int battery) {

        if (battery > 20) return;
        if (System.currentTimeMillis() - batteryAlertTime < 30 * 60 * 1000l) return;
        ;
        if (batteryDialog == null) {
            batteryDialog = new Dialog(this);
            batteryDialog.setContentView(R.layout.dialog_alert_battery);
            batteryDialog.findViewById(R.id.bt_lowbattery_ok).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    batteryDialog.dismiss();
                }
            });
            batteryDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            ViewGroup.LayoutParams lay = batteryDialog.getWindow().getAttributes();
            lay.width = ScreenUtils.getScreenWidth(this);
        }
        batteryAlertTime = System.currentTimeMillis();
        batteryDialog.show();
    }

    private String updateFileName = "firmware.zip";

    protected void enterOta() {
        if(!isBleEnable())return;
        String path = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_RES_FILEPATH);
        if (TextUtils.isEmpty(path)) return;
        if (MyApplication.getJstyleDevice() instanceof Device1810){
            DfuUtil.startDfu(this, path);
        }else {
            DfuUtil.startDfu(this, path + updateFileName);
        }

    }


    private SetPersonalInfo updateDeviceUserInfo() {
        String account = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(account);
        if(userInfo==null)return null;
        SetPersonalInfo setPersonalInfo = new SetPersonalInfo();
        Calendar calendar = Calendar.getInstance();
        int nowYear = calendar.get(Calendar.YEAR);
        int userYear = Integer.parseInt(userInfo.getBirthday().split("-")[0]);
        float height = userInfo.getHeight();
        float weight = userInfo.getWeight();
        setPersonalInfo.setAge(nowYear - userYear);
        setPersonalInfo.setHeight((int) height);
        setPersonalInfo.setWeight((int) weight);
        setPersonalInfo.setSex(userInfo.getGender() == 0 ? 1 : 0);
        return setPersonalInfo;
    }
}
